const mongoose = require("mongoose");
var url = "mongodb://root:20011219@localhost:27017/test?authSource=admin";
import mongoschema from "../schema/Schema";
import Logs from "./logs";

mongoose.connect(url, { useNewUrlParser: true, useUnifiedTopology: true });
var db = mongoose.connection;
//list connection type
db.on('error', (err)=>[
    Logs.catchError(err)
]);
db.once('open', ()=> {
    console.log("MongoDB is on!");
});
db.on('disconnected',()=> {
    Logs.catchError('Mongoose connection disconnected')
    mongoose.connect(url, { useNewUrlParser: true, useUnifiedTopology: true });
});
// const userBookListSchema = privateSchema.userBookListModel();
// const userBookList = mongoose.model('userBookLists', userBookListSchema);

class MongoDBConnection {
    user: object;
    constructor() {
        this.user = mongoose.model('user', mongoschema.user());
    }
}
const mongodbConnectin =(new MongoDBConnection()).user;


class Mongo {
    mongodbConnectin: any;
    constructor(collection: any) {
        this.mongodbConnectin = collection;
    };
    async save(data: any) {
        return new Promise((res, rej) => {
            data = this.mongodbConnectin(data)
            data.save().then(result => {
                res(result)
            }).catch(err => {
                rej(err.code)
            })
        })
    };
    async find(query?: any) {
        return new Promise((res, rej) => {
            this.mongodbConnectin.find(query).then(result => {
                res(result)
            }).catch(err => {
                rej(err)
            })
        })
    };
    async update(query: any,data:any) {
        return new Promise((res, rej) => {
            this.mongodbConnectin.updateMany(query,data, (err: any, result: any) => {
                if (err) {
                    rej(err)
                } else {
                    res(result)
                };
            })
        })
    };
    async delete(query: any) {
        return new Promise((res, rej) => {
            this.mongodbConnectin.deleteMany(query, (err: any, result: any) => {
                if (err) {
                    rej(err)
                } else {
                    res(result)
                };
            })
        })
    };
};
const mongo = new Mongo(mongodbConnectin);
export default mongo;
